package chaw.android.train;

import java.text.Collator;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import chaw.android.util.BoardItem;
import chaw.android.util.HttpRequestManager;
import chaw.android.util.LoadBitMap;
import chaw.android.util.Preferences;
import chaw.android.util.ServerURL;
import chaw.android.util.TimeCheck;

import android.app.ActivityGroup;
import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.GestureDetector.OnGestureListener;
import android.view.GestureDetector;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

public class FavoritePageListActivity extends ListActivity implements OnGestureListener{
	private ArrayList<JSONObject> json_list;
	private ArrayList<JSONObject> jlist;
	private ArrayList<BoardItem> list;
	private BoardAdapter nadapter;
	private GestureDetector gesture;
	private JSONArray json_arr;
	private String json_modify;
	private String page = "0";
	private View footer = null;
	   
    private static final int SWIPE_MIN_DISTANCE = 120;
    private static final int SWIPE_MAX_OFF_PATH = 250;
    private static final int SWIPE_THRESHOLD_VELOCITY = 200;
	 
	@Override
	public void onCreate(Bundle savedInstanceState){
		super.onCreate(savedInstanceState);
		gesture = new GestureDetector(this);
        setContentView(R.layout.favorite_page_list);
	    list = new ArrayList<BoardItem>();
	    json_list = new ArrayList<JSONObject>(); 
	    jlist = new ArrayList<JSONObject>();
	    json_modify = "";
		View lv = getListView();
		lv.setOnTouchListener(new View.OnTouchListener() {
		    @Override
			public boolean onTouch(View v, MotionEvent event) {
		    	if(gesture.onTouchEvent(event)){
	            	ActivityGroup parentActivity = (ActivityGroup) getParent();
	    			((FavoriteActivity) parentActivity).startChildActivityWithoutCurrentActivity("FavoritePeopleList",
	    						new Intent(getBaseContext(),FavoritePeopleListActivity.class));
		    	}
		    	return gesture.onTouchEvent(event);
		    }
		});
		setListView();
	}

	private void setListView(){
		DownloadAsynkTask task = new DownloadAsynkTask();
		String[] params = new String[]{ ServerURL.favoritePage, "favorite_id", Preferences.getValue(getBaseContext(), "favorite_id"), "page", page};
		task.execute(params);
	}

	private class DownloadAsynkTask extends AsyncTask<String, Void, String> {
		@Override
		protected String doInBackground(String... urls) {
			// TODO Auto-generated method stub
			String response = null;
			
			List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
			
			if(urls.length > 1)
				for(int i = 1; i< urls.length; i+=2)
					params.add(new BasicNameValuePair(urls[i], urls[i+1]));
			response = HttpRequestManager.request(urls[0], params);
			return response;
		}
		
		@Override
		protected void onPostExecute(String result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			json_modify = result;
			DownloadAsynkTask2 task = new DownloadAsynkTask2();
			task.execute(new String[]{result});
			if(page.equals("0")){

				Collections.sort(list, boardItemComparator);
				Collections.reverse(list);
				Collections.sort(jlist, boardJsonComparator);
				Collections.reverse(jlist);
				nadapter = new BoardAdapter(getBaseContext(), R.layout.favorite_page_row, R.id.board_title, list);
			    ListView lv = getListView();
			    footer = getLayoutInflater().inflate(R.layout.board_list_footer, null, false);
			    ((ImageButton)footer.findViewById(R.id.add_list)).setImageResource(R.drawable.btn_2);
			    ((ImageButton)footer.findViewById(R.id.add_list)).setOnClickListener(new View.OnClickListener() {			
					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
						int pages = new Integer(page);
						pages = pages + 10;
						page = ""+pages;
						DownloadAsynkTask task = new DownloadAsynkTask();
						String[] params = new String[]{ ServerURL.favoritePage, "favorite_id", Preferences.getValue(getBaseContext(), "favorite_id"), "page", page};
						task.execute(params);
		            }
				});

			    lv.addFooterView(footer);
			    lv.setAdapter(nadapter);
			    footer.setVisibility(View.GONE);
			}
		}
	}

	private class DownloadAsynkTask2 extends AsyncTask<String, Void, String> {
		@Override
		protected String doInBackground(String... urls) {
			String response = null;
			json_list.clear();
			JSONObject json;
			try {
				json = new JSONObject(urls[0]);
				json_arr = new JSONArray(json.get("boards").toString());
				for(int i = 0 ; i < json_arr.length(); i++){
					JSONObject json_obj = (JSONObject) json_arr.get(i);
					json_list.add(json_obj);
				}
				for(int i = 0 ; i < json_list.size() ; i++){
					JSONObject json_obj = json_list.get(i);
					JSONObject get = (JSONObject) json_obj.get("theme");
					Bitmap image_url = null;
					if(json_obj.get("image_main").toString().equals("0")){
						image_url = null;
					}
					else if(json_obj.get("image_main").toString().equals("1")){
						image_url = LoadBitMap.fromURL(json_obj.get("image_url_1").toString());
					}
					else if(json_obj.get("image_main").toString().equals("2")){
						image_url = LoadBitMap.fromURL(json_obj.get("image_url_2").toString());
					}
					else if(json_obj.get("image_main").toString().equals("3")){
						image_url = LoadBitMap.fromURL(json_obj.get("image_url_3").toString());
					}
					else if(json_obj.get("image_main").toString().equals("4")){
						image_url = LoadBitMap.fromURL(json_obj.get("image_url_4").toString());
					}
					else{
						image_url = null;
					}
					list.add(new BoardItem((String)json_obj.get("board_id"), (String)json_obj.get("title"), (String)get.get("meet"), (String)get.get("restaurant"), 
							(String)get.get("place"), (String)get.get("lodge"), (String)get.get("etc"), image_url,(String)json_obj.get("date"),"", "0"));
					list.get(list.size()-1).setStationName(json_obj.getString("station_name"));
					jlist.add(json_obj);
				}
				response = json.get("next_count").toString();
			} catch (JSONException e) {
				e.printStackTrace();
			}
			return response;
		}
		
		@Override
		protected void onPostExecute(String result) {
			super.onPostExecute(result);
			if(result != null){
				int next = new Integer(result);
				ListView lv = getListView();
				if(next == 0){
					lv.removeFooterView(footer);
				}
				if(nadapter != null){
					nadapter.notifyDataSetChanged();
				    footer.setVisibility(View.VISIBLE);
				}
			}
		}
	}

	private final static Comparator<BoardItem> boardItemComparator= new Comparator<BoardItem>() {
		private final Collator collator = Collator.getInstance();
		@Override
		public int compare(BoardItem object1,BoardItem object2) {
			return collator.compare(object1.getDate(), object2.getDate());
		}
	};
	private final static Comparator<JSONObject> boardJsonComparator= new Comparator<JSONObject>() {
		private final Collator collator = Collator.getInstance();
		@Override
		public int compare(JSONObject object1, JSONObject object2) {
			// TODO Auto-generated method stub
			String date1 = "";
			String date2 = "";
			try {
				date1 = object1.get("date").toString();
				date2 = object2.get("date").toString();
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return collator.compare(date1, date2);
		}
	};




	@Override
	public void onListItemClick(ListView parent, View v, int position, long id){
		BoardItem output = list.get(position);
		String out = output.getId();
		Intent intent = new Intent(getBaseContext(), ProfileBoardViewActivity.class);
		intent.putExtra("board_id", out);
		intent.putExtra("user_id", Preferences.getValue(getBaseContext(), "user_id"));
		startActivity(intent);
	}

	private class BoardAdapter extends ArrayAdapter<BoardItem>{
		private ArrayList<BoardItem> items;
		private int rsrc;
		
		public BoardAdapter(Context ctx, int rsrcId, int txtId, ArrayList<BoardItem> data){
			super(ctx, rsrcId, txtId, data);
			this.items = data;
			this.rsrc = rsrcId;
		}
		
		@Override
		public View getView(int position, View convertView, ViewGroup parent){
			View v = convertView;
			if(v == null){
				LayoutInflater li = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
				v = li.inflate(rsrc, null);
			}
			BoardItem e = items.get(position);
			if(e != null){
				String title = e.getTitle();
				if(title.length() > 14){
					title = title.substring(0, 13) + "..";
				}
				((TextView)v.findViewById(R.id.board_title)).setText(title);
				((TextView)v.findViewById(R.id.time)).setText(TimeCheck.checkTime(e.getDate()));
				if(!e.getReplyCount().equalsIgnoreCase("0")){
					((TextView)v.findViewById(R.id.reply_count)).setText(e.getReplyCount());
					((TextView)v.findViewById(R.id.reply_count)).setBackgroundResource(R.drawable.bg_count);
				}
				((TextView)v.findViewById(R.id.stationName)).setText(e.getStationName());

				ImageView image = ((ImageView)v.findViewById(R.id.user_pic));
				if(e.getImage() == null ){
					image.setImageResource(R.drawable.icon_nophoto_b);
				}
				else{
					image.setImageBitmap(e.getImage());
				}
				ImageView i = (ImageView)v.findViewById(R.id.theme1);
				if(e.getMeet().equals("1")){
					i.setImageResource(R.drawable.icon_theme_meet);
					i = nextIcon(v,i);
				}
				if(e.getRestaurant().equals("1")){
					i.setImageResource(R.drawable.icon_theme_food);
					i = nextIcon(v,i);
				}
				if(e.getPlace().equals("1")){
					i.setImageResource(R.drawable.icon_theme_tour);
					i = nextIcon(v,i);
				}
				if(e.getLodge().equals("1")){
					i.setImageResource(R.drawable.icon_theme_lodge);
					i = nextIcon(v,i);
				}
				if(e.getEtc().equals("1")){
					i.setImageResource(R.drawable.icon_theme_etc);
					i = nextIcon(v,i);
				}
				v = iconReset(v, i);
			}
			return v;
		}
		public ImageView nextIcon(View v, ImageView i){
			if(i.equals(v.findViewById(R.id.theme1))){
				i = (ImageView)v.findViewById(R.id.theme2);
			}
			else if(i.equals(v.findViewById(R.id.theme2))){
				i = (ImageView)v.findViewById(R.id.theme3);
			}
			else if(i.equals(v.findViewById(R.id.theme3))){
				i = (ImageView)v.findViewById(R.id.theme4);
			}
			else if(i.equals(v.findViewById(R.id.theme4))){
				i = (ImageView)v.findViewById(R.id.theme5);
			}
			return i;
		}
		public View iconReset(View v, ImageView i){
			if(i.equals(v.findViewById(R.id.theme1))){
				((ImageView)v.findViewById(R.id.theme1)).setImageDrawable(null);
				i = (ImageView)v.findViewById(R.id.theme2);
			}
			if(i.equals(v.findViewById(R.id.theme2))){
				((ImageView)v.findViewById(R.id.theme2)).setImageDrawable(null);
				i = (ImageView)v.findViewById(R.id.theme3);
			}
			if(i.equals(v.findViewById(R.id.theme3))){
				((ImageView)v.findViewById(R.id.theme3)).setImageDrawable(null);
				i = (ImageView)v.findViewById(R.id.theme4);
			}
			if(i.equals(v.findViewById(R.id.theme4))){
				((ImageView)v.findViewById(R.id.theme4)).setImageDrawable(null);
				i = (ImageView)v.findViewById(R.id.theme5);
			}
			if(i.equals(v.findViewById(R.id.theme5))){
				((ImageView)v.findViewById(R.id.theme5)).setImageDrawable(null);
			}
			return v;
		}
	}
    @Override
	public boolean onTouchEvent(MotionEvent me) {
        return gesture.onTouchEvent(me);
    }
	@Override
	public boolean onDown(MotionEvent e) {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
		// TODO Auto-generated method stub
        try {
            if (Math.abs(e1.getY() - e2.getY()) > SWIPE_MAX_OFF_PATH)
                return false;
            
            // left to right swipe
            if (e2.getX() - e1.getX() > SWIPE_MIN_DISTANCE
                    && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
        		return true;
            }
            else{
            	return false;
            }
        } catch (Exception e) {
    		return false;
            
        }
 
	}

	@Override
	public void onLongPress(MotionEvent e) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public void onShowPress(MotionEvent e) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public boolean onSingleTapUp(MotionEvent e) {
		// TODO Auto-generated method stub
		return false;
	}
	

	public boolean onCreateOptionsMenu(Menu menu){
		menu.add(0, 1 , 0 , "책갈피 수정");
		return true;
	}
	
	public boolean onOptionsItemSelected(MenuItem item){
		switch(item.getItemId()){
		case 1:
			if(!json_modify.equals("")){
				Intent intent = new Intent(getBaseContext(), ModifyPageListActivity.class);
				intent.putExtra("modify_list", json_modify);
				startActivity(intent);
				return true;
			}
			else{
				return false;
			}
		}
		return false;
	}

}
